Deques are a generalization of stacks and queues. Deques support thread-safe, memory efficient appends and pops from either side of the deque with approximately the same O(1) performance in either direction.

Though list objects support similar operations, they are optimized for fast fixed-length operations and incur O(n) memory movement costs for pop(0) and insert(0, v) operations which change both the size and position of the underlying data representation.

collections.deque([iterable[, maxlen]])¶
Returns a new deque object initialized left-to-right (using append()) with data from iterable. If iterable is not specified, the new deque is empty.


In [ ]:
from collections import deque
d = deque('MIT')
for element in d:
    print (element.lower())

In [ ]:
d.append('a')
print(d)

In [ ]:
d.appendleft('b')
print(d)

In [ ]:
d.pop()

In [ ]:
d.popleft()

In [ ]:
print(d)

In [ ]:
list(d)

In [ ]:
d = deque('stanford', 8)
print(d)

In [ ]:
d.append('z')
print(d)

In [ ]:
d.appendleft('s')
print(d)

Almost all the methods that are available for lists works for deque also. You can try them yourself.